#include<iostream>
#include<cstdint>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<string>
#include<cstring>
#include"Logger.hpp"

void Usage(std::string proc)
{
    std::cerr << "Usage: " << proc << " serverip serverport" << std::endl;
}

//./client serverip serverport
int main(int argc , char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        return 0;
    }

    uint16_t serverport = std::stoi(argv[2]);
    std::string serverip = argv[1];

    //创建套接字
    int sockfd = socket(AF_INET , SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        LOG(LogLevel::FATAL) << "创建 socket 失败" ;
        exit(0);
    }
    LOG(LogLevel::INFO) << "创建 socket 成功" ;

    //客户端的socket os 在我们第一次使用的时候会自动绑定
    //需要填写服务器的信息
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    //主机转网络
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    //客户端也是死循环
    while(true)
    {
        std::cout << "Please enter# ";
        //向文件中写数据
        std::string line;
        std::getline(std::cin , line);


        //向文件中写入 -> sendto
        sendto(sockfd , line.c_str() , line.size() , 0  , (struct sockaddr*)&server , sizeof(server));

        //客户端可以连接多个服务端
        struct sockaddr_in temp;//输出型参数
        socklen_t len = sizeof(temp);//输入、输出型参数
        char buffer[1024];
        //从文件中读取数据
        int m = recvfrom(sockfd, buffer , sizeof(buffer) , 0 ,(struct sockaddr*)&temp , &len);
        if(m > 0)
        {
            buffer[m]=0;
            std::cout << buffer << std::endl;
        }
    }

    return 0;
}